package com.yanqu.road.server.manger.mogulbirthday;

import com.yanqu.road.dao.impl.mogulbirthday.MogulBirthdayRecordDataDaoImpl;
import com.yanqu.road.entity.mogulbirthday.MogulBirthdayRecordData;
import com.yanqu.road.entity.mogulbirthday.MogulBirthdayUserData;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.date.DateHelper;

import java.util.Map;

public class MogulBirthdayMgr extends TempMgr {

    private static Map<Long, MogulBirthdayRecordData> recordDataMap;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        long today = DateHelper.getTodayZeroTime();
        recordDataMap = new MogulBirthdayRecordDataDaoImpl().getMogulBirthdayRecordData(today);
        return true;
    }


    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (Map.Entry<Long, MogulBirthdayRecordData> dataEntry : recordDataMap.entrySet()) {
            MogulBirthdayRecordData data = dataEntry.getValue();
            if(data.isInsertOption()){
                new MogulBirthdayRecordDataDaoImpl().add(data);
            }else if(data.isUpdateOption()){
                new MogulBirthdayRecordDataDaoImpl().update(data);
            }
        }
        return true;
    }

    public static void statPosterGet(long userId, long today) {
        MogulBirthdayRecordData recordData = recordDataMap.get(userId);
        if(recordData == null){
            synchronized (recordDataMap){
                recordData = recordDataMap.get(userId);
                if(recordData == null){
                    recordData = new MogulBirthdayRecordData();
                    recordData.setUserId(userId);
                    recordData.setToday(today);
                    recordData.setInsertOption();
                }
            }
        }
        synchronized (recordData){
            recordData.setGetGiftNum(1 + recordData.getGetGiftNum());
            if(recordData.isInsertOption()){
                recordDataMap.put(userId, recordData);
            }
        }
    }
}
